﻿
using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;

namespace iTool.SQL.AIHandle.ColumnRef
{
    public class SqlColumnRefExpressionAnalysis : SqlAnalysisBase
    {
        public SqlColumnRefExpressionAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            var expression = (SqlColumnRefExpression)base.CodeObject;
            string fieldName = expression.ColumnName.ToString().ToUpper();
            if (base.CodeObject.Parent is SqlColumnAssignment)
            {
                base.Context.SetFields.Add(fieldName);
            }

            if (base.CodeObject.Parent is SqlOrderByItem)
            {
                foreach (var item in base.Context.SortByOptions)
                {
                    if (item.SubIndex == this.Context.SubIndex)
                    {
                        item.Fields.Add(fieldName);
                    }
                }
            }

            base.Context.Fields.Add(new KeyValuePair<string, string>(String.Empty, fieldName));

            //System.Console.WriteLine(this.GetType().Name);
            //System.Console.WriteLine(base.CodeObject.Sql + "\n");
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
